package YahooFinance;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Klassische Implementierung des Singleton-Patterns
 */
public class MarketDataBeanRepository {

	private static MarketDataBeanRepository instance = null;
	private HashMap<StockID, MarketDataBean> stockData = new HashMap<StockID, MarketDataBean>();

	/**
	 * Default-Konstruktor, der nicht außerhalb dieser Klasse aufgerufen werden
	 * kann
	 */
	private MarketDataBeanRepository() {
	}

	/**
	 * Statische Methode, liefert die einzige Instanz dieser Klasse zurück
	 */
	public static MarketDataBeanRepository getInstance() {
		if (instance == null) {
			instance = new MarketDataBeanRepository();
		}
		return instance;
	}

	public void putToRepo(MarketDataBean pMarketDataBean) {
		StockID lStockID = new StockID(pMarketDataBean.symbol,
				pMarketDataBean.date);
		stockData.put(lStockID, pMarketDataBean);
	}

	public void writeAllEntriesToConsole() {
		Set<Entry<StockID, MarketDataBean>> stockSet = stockData.entrySet();
		for (Entry entry : stockSet) {
			System.out.println(entry.getKey()
					+ "-->"
					+ String.valueOf(((MarketDataBean) entry.getValue())
							.getPrice()));
		}
	}

	public MarketDataBean getLatestBeanData(String stockSymbol) {
		MarketDataBean latestBean = new MarketDataBean();
		Date date1 = new Date();
		Calendar c = Calendar.getInstance();  
	     c.set(Calendar.MONTH, Calendar.MARCH);  
	     c.set(Calendar.DAY_OF_MONTH, 20);  
	     c.set(Calendar.YEAR, 2000);
		date1.setTime(c.getTimeInMillis());
		latestBean.setDate(date1);
		if (stockData != null) {
			Set<StockID> keySet = stockData.keySet();
			for (StockID stockID : keySet) {
				Date actualDate = stockID.getTimestamp();
				if (actualDate.after(latestBean.getDate())) {
					latestBean = stockData.get(stockID);
				}
			}
		}
		
		return latestBean;
	}
}